package com.sky.aop;

import com.sky.annotate.AuotFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Set;

@Aspect
@Component
@Slf4j
public class MyAop {
    @Autowired
    @Qualifier("redisTemplate")
    RedisTemplate redisTemplate;

    //  公共字段 自动填充
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotate.AuotFill)")
    public void annotate_AutoFill() {}
    @Before("annotate_AutoFill()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        OperationType value = methodSignature.getMethod().getAnnotation(AuotFill.class).value();

        Object[] args = joinPoint.getArgs();
        Object arg = args[0];
        Method setCreateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
        Method setCreateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
        Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
        Method setUpdateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
        if (value == OperationType.INSERT) {
            setCreateTime.invoke(arg, LocalDateTime.now());
            setCreateUser.invoke(arg, BaseContext.getCurrnetId());
        }
        setUpdateUser.invoke(arg, BaseContext.getCurrnetId());
        setUpdateTime.invoke(arg, LocalDateTime.now());

    }

/*    // 清除所有缓存
    @Pointcut("@annotation(com.sky.annotate.DropRedis)")

    public void dropRedisPointcut() {}

    @AfterReturning("dropRedisPointcut()")
    public void dropRedis() {
        redisTemplate.opsForValue().set("123456","123456");
        System.out.println("前key"+redisTemplate.delete("*"));
        Set keys = redisTemplate.keys("*");
        for (Object key : keys) {
            redisTemplate.delete(keys);
        }
        System.out.println("key"+redisTemplate.keys("*"));
        log.error("已经清除所有的缓存!!!");
    }*/
}
